package xkp.lesson3;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        //服务端要支持多个Socket
        System.out.println("等待客户端连接.....");
        while(true){
            //主线程此处循环等待客户端连接
            Socket socket = serverSocket.accept();
            System.out.println(socket.getRemoteSocketAddress().toString()+"连接成功");
            //每来一个socket专门启动一个线程接收文件
            new RevFileThread(socket).start();
        }
    }
}


class RevFileThread extends Thread{
    private Socket socket;
    public RevFileThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            revFile(socket);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void revFile(Socket socket) throws IOException {
        //1、首先接收文件名称
        DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
        String fileName = dataInputStream.readUTF();
        String dirPath = "D:\\network";
        if(!new File(dirPath).exists()){
            new File(dirPath).mkdirs();
        }
        //2、读取文件数据，存入新文件
        String newFilePath = dirPath+File.separator+fileName;

        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
                new FileOutputStream(newFilePath));
        byte[] buf = new byte[1024];
        int length = dataInputStream.read(buf);
        while(length != -1){
            bufferedOutputStream.write(buf,0,length);
            length = dataInputStream.read(buf);
        }
        dataInputStream.close();
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
        socket.close();
    }
}